package com.tanhua.server.interceptor;

import com.tanhua.server.pojo.User;
import com.tanhua.server.service.UserService;
import com.tanhua.server.utils.NoAuthorization;
import com.tanhua.server.utils.UserThreadLocal;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 思路:自定义一个注解,如果有方法不需要权限的认证则加上这个注解
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断.请求的方法是否包含了NoAuthorization注解,如果包含了,就不需要做处理
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            NoAuthorization annotation = handlerMethod.getMethod().getAnnotation(NoAuthorization.class);
            if (annotation != null) {
                return true;
            }
        }

        //初始化
        UserThreadLocal.set(null);

        String token = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(token)) {
            User user = userService.queryUserByToken(token);
            if (user != null) {
                //存储到当前线程中
                UserThreadLocal.set(user);
                return true;
            }
        }

        response.setStatus(401);   //无权限
        return false;
    }
}
